<template>
    <div style="border: 1px solid #ccc;padding: 10px">
        <div class="tag-group" v-if="tags && tags.length>0">
            <span class="tag-group__title">已选中</span>
            <el-tag
                    v-for="item in tags"
                    :key="item.name"
                    closable
                    @close="handleTagClose(item)"
                    style="margin-left: 10px"
            >
                {{ item.name }}
            </el-tag>
            <div style="border-top: 1px solid #ccc;margin-top: 10px;margin-bottom: 10px"/>
        </div>

        <!--国选择-->
        <div v-if="addressList">
            <!--<div style="margin: 15px 0;">国家</div>-->
            <el-checkbox v-for="data in addressList" :label="data.id" :key="data.id" v-model="data.check"
                         :indeterminate="data.indeterminate"
                         v-on:change="clickNodeCheck(data)">
                <span v-on:click.stop.prevent="clickNodeContent(data) ">{{data.name}}</span>
            </el-checkbox>
        </div>

        <!--省选择-->
        <div v-if="level1List&&level1List.length>0">
            <div style="margin: 15px 0;">省份</div>
            <el-checkbox v-for="data in level1List" :label="data.id" :key="data.id"
                         v-model="data.check"
                         :indeterminate="data.indeterminate"
                         v-on:change="clickNodeCheck(data)">
                <span v-on:click.stop.prevent="clickNodeContent(data)"
                      v-bind:class="{ active: provinceIsActive(data)}"
                >{{data.name}}</span>
            </el-checkbox>
        </div>

        <!--市选择-->
        <div v-if="level2List&&level2List.length>0">
            <div style="margin: 15px 0;">城市</div>
            <el-checkbox v-for="data in level2List" :label="data.id"
                         :key="data.id" v-model="data.check"
                         :indeterminate="data.indeterminate"
                         v-on:change="clickNodeCheck(data)">
                <span v-on:click.stop.prevent="clickNodeContent(data)"
                      v-bind:class="{ active: cityIsActive(data)}"
                >{{data.name}}</span>
            </el-checkbox>
        </div>

        <!--区选择-->
        <div v-if="level3List&&level3List.length>0">
            <div style="margin: 15px 0;">区县</div>
            <el-checkbox
                    v-for="data in level3List"
                    :label="data.id" :key="data.id" v-model="data.check"
                    :indeterminate="data.indeterminate"
                    v-on:change="clickNodeCheck(data)">
                <span v-on:click.stop.prevent="clickNodeContent(data)"
                      v-bind:class="{ active: areaIsActive(data)}"
                >{{data.name}}</span>
            </el-checkbox>
        </div>
    </div>
</template>

<script>
    export default {
        name: 'hucaiAreaSelect',
        props: ['addressList', 'rootAddress', 'resultJson'],
        //展示数据、根数据、返回后台的数据
        data() {
            return {
                //当前vue的本地变量
                tags: [],//标签的值，显示条件：1.父节点为不确定状态 2.没有子节点或子节点全是选中状态
                levelIndex: [0, -1, -1, -1],//国，省，市，区  各级选中索引
            }
        }, mounted() {
            this.initMethod();
        }, computed: {
            //省是否显示
            level1List() {
                try {
                    let b = this.addressList[0].children
                    return b
                } catch (e) {
                    return false
                }
            },
            //市是否显示
            level2List() {
                try {
                    let b = this.addressList[0].children[this.levelIndex[1]].children
                    return b
                } catch (e) {
                    return false
                }
            },
            //省是否显示
            level3List() {
                try {
                    let b = this.addressList[0].children[this.levelIndex[1]].children[this.levelIndex[2]].children
                    return b
                } catch (e) {
                    return false
                }
            }
        }, methods: {
            //省是否激活
            provinceIsActive(data) {
                var selectNode = this.addressList[0].children[this.levelIndex[1]];
                if (selectNode) {
                    return data.id === selectNode.id;
                }
                return false;
            },
            //市是否激活
            cityIsActive(data) {
                var selectNode = this.addressList[0].children[this.levelIndex[1]].children[this.levelIndex[2]];
                if (selectNode) {
                    return data.id === selectNode.id;
                }
                return false;
            },
            //区是否激活
            areaIsActive(data) {
                var selectNode = this.addressList[0].children[this.levelIndex[1]].children[this.levelIndex[2]].children[this.levelIndex[3]];
                if (selectNode) {
                    return data.id === selectNode.id;
                }
                return false;
            },
            //初始化方法
            clickNodeCheck(value) {
                console.log("asssssss", value);
                //遍历所有父节点，设置不确定或全选状态
                var node = this.getNodeById(this.addressList[0], value.pid)
                console.log("33333333", node);
                while (node) {
                    //设置节点的选中状态
                    this.setNodeStatus(node);
                    node = this.getNodeById(this.addressList[0], node.pid)
                }
                //设置子节点状态
                const checkChildrenNotCheck = function (data) {
                    data.children.forEach(function (row) {
                        row.check = value.check;
                        checkChildrenNotCheck(row)
                    })
                }
                //设置子节点状态
                checkChildrenNotCheck(value);


                //设置节点的选中状态
                // this.setNodeStatus(value);
                //
                this.initOther();
            },
            //节点内容的单击事件
            initMethod() {
                if (this.addressList.length === 0) {
                    //初始加载全国
                    this.addressList.push(this.rootAddress)
                    this.loadData(this.addressList[0])//加载省数据
                } else {
                    this.initOther();
                }
            },
            //设置当前节点的选择状态和不确定状态
            setNodeStatus(node){
                var brotherNodeSize = node.children.length//同级节点的数量
                var brotherNodeCheckSize = 0//同级节点的选中数量
                var brotherNodeIndeterminateSize = 0//同级节点的不确定数量
                node.children.forEach(function (row) {
                    if (row.check) {
                        brotherNodeCheckSize++
                    }
                    if (row.indeterminate) {
                        brotherNodeIndeterminateSize++
                    }
                })
                if (brotherNodeCheckSize === 0) {
                    console.log("55555555 brotherNodeSize=,brotherNodeCheckSize,brotherNodeIndeterminateSize", brotherNodeSize, brotherNodeCheckSize, brotherNodeIndeterminateSize)
                    node.check = false
                    node.indeterminate = false
                } else if (brotherNodeSize !== brotherNodeCheckSize) {
                    node.check = true
                    console.log("111 brotherNodeSize=,brotherNodeCheckSize", brotherNodeSize, brotherNodeCheckSize)
                    node.indeterminate = true
                } else if (brotherNodeSize === brotherNodeCheckSize) {
                    console.log("44444 brotherNodeSize=,brotherNodeCheckSize,brotherNodeIndeterminateSize", brotherNodeSize, brotherNodeCheckSize, brotherNodeIndeterminateSize)
                    node.check = true
                    node.indeterminate = false
                }
                if (brotherNodeIndeterminateSize > 0) {
                    console.log("2222 brotherNodeSize=,brotherNodeCheckSize,brotherNodeIndeterminateSize", brotherNodeSize, brotherNodeCheckSize, brotherNodeIndeterminateSize)
                    node.indeterminate = true
                }
            },
            //节点复选框的单击事件
            clickNodeContent(data) {
                var node = this.getNodeById(this.addressList[0], data.pid)
                if (node) {
                    let index = node.children.indexOf(data)
                    this.$set(this.levelIndex, data.level, index)
                }
                this.loadData(data)
            },
            initOther() {
                this.tags = [];
                this.setTags(this.addressList[0], false, false);
                //先清空resultJson
                this.resultJson.splice(0, this.resultJson.length)
                //深拷贝对象
                var copyRootAddress = JSON.parse(JSON.stringify(this.addressList))
                this.setResultJson(copyRootAddress[0], false, false);
                if (copyRootAddress[0].check || copyRootAddress[0].indeterminate) {
                    this.resultJson.push(copyRootAddress[0]);
                }
            },
            //复选框的选择事件
            handleCheckedChange(value) {
            },
            //处理值tag关闭事件
            handleTagClose(value) {
                value.check = false;
                value.indeterminate = false;
                this.clickNodeCheck(value);
            },
            //调用父组件动态加载数据
            loadData(node) {
                this.$emit('load-data', node, this.appendData)
            },
            //父组件成功获取值后的回调
            appendData(addlist, node) {
                if (!node.children || node.children.length === 0) {
                    node.children = []
                    for (var i = 0; i < addlist.length; i++) {
                        addlist[i].children = []
                        addlist[i].check = node.check//如果父是选中状态，则加载的节点也是选择状态
                        node.children.push(addlist[i])
                    }
                }
            },
            //根据id获取节点
            getNodeById(node, id) {
                var resultNode = null
                const getNodeById2 = function (data) {
                    if (data.id === id) {
                        resultNode = data
                    } else {
                        data.children.forEach(function (row) {
                            getNodeById2(row)
                        })
                    }
                }
                getNodeById2(node)
                return resultNode
            },
            //根据id获取节点
            setTags(node, check, indeterminate) {
                //node=当前节点，isCheck=父节点是否选中
                var brotherNodeSize = node.children.length//同级节点的数量
                var brotherNodeCheckSize = 0//同级节点的选中数量
                var brotherNodeIndeterminateSize = 0//同级节点的不确定数量
                node.children.forEach(function (row) {
                    if (row.check) {
                        brotherNodeCheckSize++
                    }
                    if (row.indeterminate) {
                        brotherNodeIndeterminateSize++
                    }
                })

                if ((node.check && !node.indeterminate) && (!check || indeterminate) && (brotherNodeSize === 0 || brotherNodeSize === brotherNodeCheckSize)) {
                    this.tags.push(node);
                }

                var that = this;
                node.children.forEach(function (row) {
                    that.setTags(row, node.check, node.indeterminate);
                })
            },
            //设置最终返回的json
            setResultJson(node, check, indeterminate) {
                //node=当前节点，isCheck=父节点是否选中
                var brotherNodeSize = node.children.length//同级节点的数量
                var brotherNodeCheckAndIndeterSize = 0//同级节点的选中数量
                node.children.forEach(function (row) {
                    if (row.check) {
                        brotherNodeCheckAndIndeterSize++
                    }
                    if (row.indeterminate) {
                        brotherNodeCheckAndIndeterSize++
                    }
                })

                //如果子节点全是不选或全选，删除所有节点
                var isDeleteAll = brotherNodeSize === brotherNodeCheckAndIndeterSize;
                for (var i = (node.children.length - 1); i >= 0; i--) {
                    var row = node.children[i];
                    if (isDeleteAll || (!row.check && !row.indeterminate)) {
                        node.children.splice(i, 1);
                    }
                }

                var that = this;
                node.children.forEach(function (row) {
                    that.setResultJson(row, node.check, node.indeterminate);
                })
            },
        }
    }
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
    .active {
        color: red;
    }
</style>
